Spawner / LNMTL - Translation Improved [ DEBUG ]

// ==UserScript==
// @name        LNMTL - Translation Improved [ DEBUG ]
// @namespace   justtesting
// @match       https://lnmtl.com/chapter/*
// @grant       GM_xmlhttpRequest
// @grant       GM_addStyle
// @grant       GM_setValue
// @grant       GM_getValue
// @require      https://userscripts-mirror.org/scripts/source/107941.user.js#sha384=Q8t880BurrlGKTdpvYv2+da12PYnvljdiU8aJvakk1uE3QMbzb190ueXNpAUY98p
// @version     1.0.1
// @author      Spawner
// @license     MIT
// @description 3/21/2020, 10:06:19 AM
// ==/UserScript==

/* CSS STYLES */

GM_addStyle("hgltr { color:#5352ed }");
GM_addStyle(".niut { color:white; font-size: 2.2rem; margin-bottom:42px; font-family: droidSerif }");

/* VARIABLES */

var uniqueWords = new Map();

var translationService  = GM_SuperValue.get('translationService', "");
var autoNiuTransOn      = GM_SuperValue.get('autoNiuTransOn'    , false);
var autoShow_SOn          = GM_SuperValue.get('autoShow_SOn'    , false);
var autoGlow_SOn          = GM_SuperValue.get('autoGlow_SOn'    , false);

var isTranslated = false;
var extractRaw;

window.onload = async function () 
{
    replaceRaws();
    createBtnUI();
    createSettings();
  
    $( '.translated t' ).each( function ( index )
    {
      var value = $( this )
                    .attr( 'data-title', $( this ).text() )
                    .text()
                    .trimLeft();
      
      uniqueWords.set( value, index );
    } );
  
    extractRaw = $('.original').text().trimStart().replace(/\n/g, '%0A');
    
    var myData = [];
    myData = await sendRequest(extractRaw);
    
    createSentence( myData );
}

function sendRequest( rawText )
{
    return new Promise( ( resolve ) =>
    {
      GM_xmlhttpRequest(
      {
          method  : "GET",
          url     : "http://test.niutrans.vip/NiuTransServer/testtrans?&from=zh&to=en&src_text=" + rawText
          ,
          onload: function ( result ) 
          {
              var myResponse = JSON.parse( result.response ).tgt_text;
              //console.log( myResponse );
              resolve( myResponse.split('\n') ) 
              isTranslated = true;
          }
      });
    });
}

function createSentence( gtpars )
{
    gtpars.forEach( ( sentence, index ) =>
    {
      if ( autoGlow_SOn )
      {
        for ( const [ key, value ] of uniqueWords.entries() )
            sentence = sentence.replace( new RegExp( '(\\b)(' + key + ')(\\b)', 'gi' ), '<span style="color:#52a9ff">' + key + '</span>' );
      }

      $( '.translated' ).eq( index ).after( "<div class='niut' tab-index=0><sentence data-index=" + index + ">" + sentence + "</sentence></div>" );
    });
}

function createBtnUI()
{
    $( '.js-toggle-original' ).after( '<button class="btn btn-enabled js-toggle-niut">NIUT</button>' );

    $( '.btn.btn-enabled.js-toggle-niut' )[ 0 ].style.borderColor  = "white";
    $( '.btn.btn-enabled.js-toggle-niut' )[ 0 ].style.boxShadow    = "0px 0px 20px #ecf0f1";
    $( '.btn.btn-enabled.js-toggle-niut' )[ 0 ].style.color        = "orange";

    $( '.js-toggle-niut' ).click( function ()
    {
        isTranslated ? $( ".niut" ).toggle( { duration: 200 } ) : sendRequest( extractRaw );
    })
      .text( 'NIUT' ).addClass( 'btn-default' );
}

function createSettings()
{
    let title = $( '<h3> Improved Translation Settings </h3>' );
    let checked = autoNiuTransOn ? 'checked' : '';
    let optionAutoswitch = $( '<sub><input id="autoNiuTransOn" type="checkbox" ' + checked + '></sub> <label for="autoNiuTransOn">Automatically display NiuTrans translation after loading the page.</label>' )
      .on( 'change', function ()
      {
        autoNiuTransOn = $( '#autoNiuTransOn' )[ 0 ].checked;
        GM_SuperValue.set( 'autoNiuTransOn', autoNiuTransOn );
      });

    let checked2 = autoGlow_SOn ? 'checked' : '';
    let optionGlow = $( '<sub><input id="autoGlow_SOn" type="checkbox" ' + checked2 + '></sub> <label for="autoGlow_SOn">Apply the Glow word highlighter.</label>' )
      .on( 'change', function ()
      {
        autoGlow_SOn = $( '#autoGlow_SOn' )[ 0 ].checked;
        GM_SuperValue.set( 'autoGlow_SOn', autoGlow_SOn );
      });

    let checked3 = autoShow_SOn ? 'checked' : '';
    let optionShow = $( '<sub><input id="autoShow_SOn" type="checkbox" ' + checked3 + '></sub> <label for="autoShow_SOn"><span style="color:rgb(26, 188, 156)">Show only Translation.</span></label>' )
      .on( 'change', function ()
      {
        autoShow_SOn = $( '#autoShow_SOn' )[ 0 ].checked;
        GM_SuperValue.set( 'autoShow_SOn', autoShow_SOn );
      });

    let row = $( '<div class="row"/>' );

    $( "#chapter-display-options-modal .modal-body" )
      .append( title )
      .append( optionAutoswitch ).append( '<br>' )
      .append( optionGlow ).append( '<br>' )
      .append( optionShow ).append( '<br>' )
      .append( '<span style="color:yellow">Changes apply after the page is reloaded.</span>' )
      .append( row );
}

function replaceRaws()
{
    $( '.original t' ).each( function ()
    {
      var mytext = $( this ).text();
      $( this ).text( $( this ).attr( 'data-title' ).replace( /\(\w+\)/g, '' ) );
      $( this ).attr( 'data-title', mytext );
    });
    // add whitespace between two english words
    $( '.original' ).find( 't' ).filter( function ( index )
    {
      var prev = $( this ).get( 0 ).previousSibling;
      return prev ? $( this ).get( 0 ).previousSibling.nodeName == 'T' : false;
    }).each( function ()
    {
      $( this ).text( ' ' + $( this ).text() );
    });
}